package com.zzyl.nursing.service.impl;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.IDCardUtils;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.ai.AIModelInvoker;
import com.zzyl.nursing.vo.HealthReportVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.HealthAssessmentMapper;
import com.zzyl.nursing.domain.HealthAssessment;
import com.zzyl.nursing.service.IHealthAssessmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

/**
 * 健康评估Service业务层处理
 *
 * @author alexis
 * @date 2025-01-06
 */
@Service
public class HealthAssessmentServiceImpl extends ServiceImpl<HealthAssessmentMapper, HealthAssessment> implements IHealthAssessmentService {
    @Autowired
    private HealthAssessmentMapper healthAssessmentMapper;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AIModelInvoker aiModelInvoker;

    /**
     * 查询健康评估
     *
     * @param id 健康评估主键
     * @return 健康评估
     */
    @Override
    public HealthAssessment selectHealthAssessmentById(Long id) {
        return healthAssessmentMapper.selectById(id);
    }

    /**
     * 查询健康评估列表
     *
     * @param healthAssessment 健康评估
     * @return 健康评估
     */
    @Override
    public List<HealthAssessment> selectHealthAssessmentList(HealthAssessment healthAssessment) {
        return healthAssessmentMapper.selectHealthAssessmentList(healthAssessment);
    }

    /**
     * 新增健康评估
     *
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public Long insertHealthAssessment(HealthAssessment healthAssessment) {
        //1.获取提示词
        String prompt = getPrompt(healthAssessment.getIdCard());

        //2将获取的结果交由AI大模型分型获取分析结果
        String qianfanResult = aiModelInvoker.qianfanInvoker(prompt);
        //3.将结果封装到对象中去
        HealthReportVo healthReportVo= JSON.parseObject(qianfanResult,HealthReportVo.class);

        //4将数据保存到数据库中



        return  saveHealthAssessment(healthAssessment,healthReportVo);
    }

    private Long saveHealthAssessment(HealthAssessment healthAssessment, HealthReportVo healthReportVo) {
        //获取出生日期
        LocalDateTime birthDateByIdCard = IDCardUtils.getBirthDateByIdCard(healthAssessment.getIdCard());
        healthAssessment.setBirthDate(birthDateByIdCard);
        //获取年龄
        int ageByIdCard = IDCardUtils.getAgeByIdCard(healthAssessment.getIdCard());
        healthAssessment.setAge(ageByIdCard);
        //获取性别
        int genderFromIdCard = IDCardUtils.getGenderFromIdCard(healthAssessment.getIdCard());
        healthAssessment.setGender(genderFromIdCard);
        //获取健康评分
        double healthIndex = healthReportVo.getHealthAssessment().getHealthIndex();
        healthAssessment.setHealthScore(String.valueOf(healthIndex));
        //获取危险等级
        healthAssessment.setRiskLevel(healthReportVo.getHealthAssessment().getRiskLevel());
        //是否建议入住
        healthAssessment.setSuggestionForAdmission((healthIndex>=60 ? 0:1));
        //推荐护理等级
        healthAssessment.setNursingLevelName(getNurSingLevel(healthIndex));

        //是否入住
        healthAssessment.setAdmissionStatus(1);
        //评估时间
        healthAssessment.setTotalCheckDate(healthReportVo.getTotalCheckDate());
        healthAssessment.setAssessmentTime(LocalDateTime.now());
        //报告总结
        healthAssessment.setReportSummary(healthReportVo.getSummarize());
        //疾病风险
        healthAssessment.setDiseaseRisk(JSON.toJSONString(healthReportVo.getRiskDistribution()));
        //异常分析
        healthAssessment.setAbnormalAnalysis(JSON.toJSONString(healthReportVo.getAbnormalData()));
        //健康系统评分
        healthAssessment.setSystemScore(JSON.toJSONString(healthReportVo.getSystemScore()));
        int insert = healthAssessmentMapper.insert(healthAssessment);
        return healthAssessment.getId();

    }
//测试护理等级d
    private String getNurSingLevel(double healthIndex) {
        if(healthIndex>100 || healthIndex<0){
            return "健康评估分数不正确";
        }
        if(healthIndex>=90){
            return "五级护理";
        } else if(healthIndex>=80){
            return "四级护理";
        } else if(healthIndex>=70){
            return "三级护理";
        } else if(healthIndex >= 60) {

            return "一级护理";
        } else {
            return "特特级护理";
        }
    }
//将体检报告的结果保存到数据库中

    //获取提示词
    private String getPrompt(String idCard) {
        try (
                //获取提示词模板
                InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("prompt\\healthReport.txt");
                InputStreamReader inputStreamReader = new InputStreamReader(resourceAsStream);
                BufferedReader bs = new BufferedReader(inputStreamReader);
        ) {

            //从缓存中获取体检报告内容
            String promptFDP = (String) redisTemplate.opsForHash().get(CacheConstants.HEALTH_REPORT, idCard);
            //从缓存中删除体检报告内容
            redisTemplate.opsForHash().delete(CacheConstants.HEALTH_REPORT,idCard);

            //拼接提示词
            StringBuilder prompt = new StringBuilder();
            String joint = null;
            while ((joint = bs.readLine())!=null) {
                prompt.append(joint);
                if (joint.contains("体检内容如下：")) {
                    prompt.append(promptFDP);
                }

            }

            //拼接提示词
            return prompt.toString();
        } catch (IOException e) {
            throw new BaseException("获取文件失败，获取提示词失败");
        }
    }

    /**
     * 修改健康评估
     *
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public int updateHealthAssessment(HealthAssessment healthAssessment) {
        return healthAssessmentMapper.updateById(healthAssessment);
    }

    /**
     * 批量删除健康评估
     *
     * @param ids 需要删除的健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentByIds(Long[] ids) {
        return healthAssessmentMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除健康评估信息
     *
     * @param id 健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentById(Long id) {
        return healthAssessmentMapper.deleteById(id);
    }
}
